package com.yinhe.music.yhmusic.utils;

import android.content.ContentUris;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.provider.MediaStore;

import com.hwangjr.rxbus.RxBus;
import com.yinhe.music.common.utils.ScanMusicUtil;
import com.yinhe.music.event.RxBusEventType;
import com.yinhe.music.event.RxbusListObject;
import com.yinhe.music.yhmusic.R;
import com.yinhe.music.yhmusic.application.MusicApplication;
import com.yinhe.music.yhmusic.cache.CacheManager;
import com.yinhe.music.yhmusic.constants.BasicConfig;
import com.yinhe.music.yhmusic.db.DataBaseAccessor;
import com.yinhe.music.yhmusic.db.bean.DownloadMusicEntity;
import com.yinhe.music.yhmusic.db.bean.SongDBEntity;
import com.yinhe.music.yhmusic.downmusic.DownloadStatus;
import com.yinhe.music.yhmusic.model.Music;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * 歌曲工具类
 * Created by wcy on 2015/11/27.
 */
public class MusicUtils {
    /**
     * 扫描歌曲
     */
    public static List<Music> scanMusic() {
        List<Music> musicList = new ArrayList<>();

        Cursor cursor = MusicApplication.getContext().getContentResolver().query(
               MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, null, null, null,
                 MediaStore.Audio.Media.DEFAULT_SORT_ORDER);

        if (cursor == null) {
            return null;
        }
        if(cursor.getCount()>0){
            while (cursor.moveToNext()) {
                // 是否为音乐
                int isMusic = cursor.getInt(cursor.getColumnIndex(MediaStore.Audio.Media.IS_MUSIC));
                if (isMusic == 0) {
                    continue;
                }
                long id = cursor.getLong(cursor.getColumnIndex(MediaStore.Audio.Media._ID));
                String title = cursor.getString((cursor.getColumnIndex(MediaStore.Audio.Media.TITLE)));
                String artist = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.ARTIST));
                int singerId = cursor.getInt(cursor.getColumnIndex(MediaStore.Audio.Media.ARTIST_ID));
                String unknown = MusicApplication.getContext().getString(R.string.unknown);
                artist = "<unknown>".equals(artist) ? unknown : artist;
                String album = cursor.getString((cursor.getColumnIndex(MediaStore.Audio.Media.ALBUM)));
                long duration = cursor.getLong(cursor.getColumnIndex(MediaStore.Audio.Media.DURATION));
                String uri = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.DATA));
                long albumId = cursor.getLong(cursor.getColumnIndex(MediaStore.Audio.Media.ALBUM_ID));
                String coverUri = getCoverUri(MusicApplication.getContext(), albumId);
                Music music = new Music();
                music.setSongId(id);
                music.setFileType(Music.Type.LOCAL);
                music.setSongName(title);
                music.setSingerName(artist);
                music.setAlbumName(album);
                music.setAlbumId(albumId);
                music.setDuration(duration);
                music.setFilePath(uri);
                music.setImage(coverUri);
                music.setSingerName(artist);
                music.setSingerId(singerId);
                music.downloadStatus = DownloadStatus.DOWNLOAD_STATUS_COMPLETED;
                musicList.add(music);
            }

            cursor.close();
        }
        return musicList;
    }

    public static List<Music> getSingerSong(List<Music> musicList,long singerId){
        List<Music> singerSong = new ArrayList<>();
        if (musicList!=null){
            for (Music music:musicList){
                if (music.getSingerId() == singerId){
                    singerSong.add(music);
                }
            }
        }
        return singerSong;
    }

    public static List<Music> getAlbumSong(List<Music> musicList,long albumbId){
        List<Music> singerSong = new ArrayList<>();
        if (musicList!=null){
            for (Music music:musicList){
                if (music.getAlbumId() == albumbId){
                    singerSong.add(music);
                }
            }
        }
        return singerSong;
    }

    public static List<Music> getFileSong(List<Music> musicList,String path){
        List<Music> fileSong = new ArrayList<>();
        if (musicList!=null){
            for (Music music:musicList){
                String oldPath = music.getFilePath();
                oldPath = oldPath.substring(0,oldPath.lastIndexOf("/"));
                if (oldPath.equals(path)){
                    fileSong.add(music);
                }
            }
        }
        return fileSong;
    }

    private static String getCoverUri(Context context, long albumId) {
        String uri = "";
        if (albumId>0){
            Cursor cursor = context.getContentResolver().query(
                    Uri.parse("content://media/external/audio/albums/" + albumId),
                    new String[]{"album_art"}, null, null, null);
            if (cursor != null && cursor.getCount()>0) {
                cursor.moveToNext();
                uri = cursor.getString(0);
                cursor.close();
            }
            CoverLoader.getInstance().loadThumbnail(uri);
        }
        return uri;
    }


    public interface CheckCallBack {
        void checkBuy(boolean needBuy);
    }

    public static List<Music> getMusicListFromSongDb(List<SongDBEntity> mList) {
        List<Music> musicList = new ArrayList<>();
        if (mList!=null){
            for (SongDBEntity songDBEntity : mList) {
                musicList.add(new Music(songDBEntity));
            }
        }
        return musicList;
    }

    public static List<Music> getMusicListFromDownDb(List<DownloadMusicEntity> mList) {
        List<Music> musicList = new ArrayList<>();
        if (mList!=null){
            for (DownloadMusicEntity downloadMusicEntity : mList) {
                musicList.add(new Music(downloadMusicEntity));
            }
        }
        return musicList;
    }

    public static void setMusicUri(SongDBEntity  songDBEntity){
        if (songDBEntity.getUri() == null){
            songDBEntity.setUri(DataBaseAccessor.getInstance().getDownMusicByDownloadIdSyn(songDBEntity.getSongid()).getUri());
            DataBaseAccessor.getInstance().updateSong(songDBEntity);
        }
    }

    private static void deleteMusic(Context mContext,Music music){
        //删除sd卡的本地歌曲
        File f = new File(music.getFilePath());
        if (f.exists()) {
            boolean flag = f.delete();
            if (flag) {
                Uri uri = ContentUris.withAppendedId(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, music.getSongId());
                mContext.getContentResolver().delete(uri, null, null);
            }
        }

        refreshLocal(mContext, music.filePath, music.filePath);
    }

    public static void deleteFile(Context mContext, DownloadMusicEntity file) {
        File f = new File(file.getUri());
        if (f.exists()) {
            boolean flag = f.delete();
            if (flag) {
                Uri uri = ContentUris.withAppendedId(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, file.getSongid());
                mContext.getContentResolver().delete(uri, null, null);
            }
        }
    }

    /*
    * 删除本地音乐
    * */
    public static void deleteLocalMusic(Context mContext,List<Music> musicList) {
        List<Integer> idList = new ArrayList<>();
        for (Music music : musicList) {
            MusicUtils.deleteMusic(mContext,music);
            if (DataBaseAccessor.getInstance().isExsitIdSyn(music.getId(), DownloadStatus.DOWNLOAD_STATUS_COMPLETED)){
                idList.add((int) music.getSongId());
            }
        }
        DataBaseAccessor.getInstance().deleteDownMusicByList(idList,false);
        RxBus.get().post(RxBusEventType.Local.DELETE_LOCAL_MUSIC, RxbusListObject.instance(musicList));
    }

    /**
     * 刷新本地媒体库
     */
    public static void refreshLocal(Context mContext, String fileName, final String filePath){
        File file = new File(BasicConfig.getInstance().getMusicDownLoadDir() +
                File.separator+ fileName);

        new ScanMusicUtil(mContext, file, new ScanMusicUtil.ScanListener() {
            @Override
            public void onScanFinish() {
                List<Music> musicList = CacheManager.getInstance().getScanMusic();
                if (musicList.size()>0){
                    for (Music music:musicList){
                        if (music.filePath.equals(filePath)){
                            musicList.remove(music);
                        }
                    }
                }
                CacheManager.getInstance().setScanMusic(musicList);
            }
        });
    }
}
